﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Configuration;
using System.Web.Security;
using System.Security.Cryptography;
using System.IO;
using System.Net.Mail;
using System.Net;

public partial class product_card_user_Machine : System.Web.UI.Page
{
    bool isCard = false;
    SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
    double totalAmount = 0;

    protected void Page_Load(object sender, EventArgs e)
    {

        String TransID = Session["transactionID"] as String;
        String custId = Session["userId"] as String;
        String limit = Session["limitLeft"] as String;


        con.Open();
        SqlCommand cmd1 = new SqlCommand("select * from APPLICATIONDEBIT where custID ='" + custId + "'", con);
        cmd1.Connection = con;
        SqlDataReader dr1 = cmd1.ExecuteReader();


        dr1.Close();
        SqlCommand cmd = new SqlCommand("select * from CHARTSPENDINGS where custID='" + custId + "'", con);


        cmd.Connection = con;

        SqlDataReader dr = cmd.ExecuteReader();

        while (dr.Read())
        {

            Total.Text = dr["limitLeft"].ToString();

            Object Quantity = Session["Quantity"];
            if (Quantity != null)
            {

                if (!Util.IsBlank((String)Quantity))
                {
                    Number.Text = "Quantity:";
                    Number.Visible = true;
                    this.Number.Text = (String)Quantity;
                    this.Number.Visible = true;

                }
                else
                {
                    Number.Visible = false;

                }

            }

            Object Item1 = Session["Product"];
            if (Item1 != null)
            {

                if (!Util.IsBlank((String)Item1))
                {
                    Type.Text = "Product:";
                    Type.Visible = true;
                    this.Type.Text = (String)Item1;
                    this.Type.Visible = true;

                }
                else
                {
                    Type.Visible = false;

                }
                Object DiscountedAmount1 = Session["Discount"];
                if (DiscountedAmount1 != null)
                {

                    if (!Util.IsBlank((String)DiscountedAmount1))
                    {
                        Cost.Text = "Discount:";
                        Cost.Visible = true;
                        this.Cost.Text = (String)DiscountedAmount1;
                        this.Cost.Visible = true;

                    }
                    else
                    {
                        Cost.Visible = false;

                    }






                }
            }
        }

    }

    protected void Clear_Click(object sender, EventArgs e)
    {


        Password.Text = "******";
        Amount.Text = "";
        ComName.Text = "";
        Card.Text = "";

    }



    protected void Button1_Click(object sender, EventArgs e)
    {

        String custId = Session["userId"] as String;
        double amount = Convert.ToDouble(Amount.Text);
        double limit = Convert.ToDouble(Total.Text);
        var ApplicationDate = DateTime.Now;


        String cardNo;
        cardNo = Convert.ToString(Card.Text);
        String result;
        result = Convert.ToString(Password.Text);

        //var gengerator = new AccountsManager();
        //string AccountNo = gengerator.GenerateNo("CARDS");
        string AccountNo = Session["savingAccountNo"] as String;
        string shopAccountNo = "5208888888"; // fix value, our only have one shop -PowerShop

        if (amount != null)
        {

            if ((limit - amount) >= 0)
            {

                SqlConnection con = DBManager.getSqlConnection();
                con.Open();
                PIN = result;
                SqlCommand cmd1 = new SqlCommand("select * from CARDGENERATOR where cardNo='" + cardNo + "'and custID = '" + custId + "' and PIN='" + PIN + "'", con);
                SqlDataReader dr = cmd1.ExecuteReader();
                if (dr.Read())
                {


                    
                    Session["cardNo"] = dr.GetString(0);
                    Session["PIN"] = dr.GetString(2);
                    dr.Close();
                    double lastLimit = limit - amount;
                    Total.Text = lastLimit.ToString();
                    String sql = "insert into Summary (transactionDate,transactionType,transactionStatus,transactionAmount,accountNo) values (@transactionDate,@transactionType,@transactionStatus,@transactionAmount,@accountNo)";
                    SqlCommand cmd = new SqlCommand(sql, con);

                    cmd.Parameters.AddWithValue("@transactionDate", ApplicationDate);
                    cmd.Parameters.AddWithValue("@transactionType","DEBIT PAYMENT");
                    cmd.Parameters.AddWithValue("@transactionStatus", "SUCCESS");
                    cmd.Parameters.AddWithValue("@transactionAmount", 0 - decimal.Parse(Amount.Text));
                    cmd.Parameters.AddWithValue("@accountNo", AccountNo);
                    cmd.ExecuteNonQuery();


                    cmd = new SqlCommand(sql, con);
                    cmd.Parameters.AddWithValue("@transactionDate", ApplicationDate);
                    cmd.Parameters.AddWithValue("@transactionType", "DEBIT PAYMENT");
                    cmd.Parameters.AddWithValue("@transactionStatus", "SUCCESS");
                    cmd.Parameters.AddWithValue("@transactionAmount", decimal.Parse(Amount.Text));
                    cmd.Parameters.AddWithValue("@accountNo", shopAccountNo);

                    cmd.ExecuteNonQuery();

                    cmd = new SqlCommand("insert into POSPurchase values('" + custId + "','" + cardNo + "','" + ComName.Text + "','" + Type.Text + "','" + Number.Text + "','" + Cost.Text + "','" + Amount.Text + "','" + Total.Text + "','" + PIN + "')", con);
                    cmd.ExecuteNonQuery();
                    SqlCommand cmd5 = new SqlCommand("UPDATE ChartSpendings SET spentAmount = (spentAmount+@spentAmount), limitLeft= @limitLeft  WHERE custID = @custID", con);
                    cmd5.Parameters.Add("spentAmount", Amount.Text);
                    cmd5.Parameters.Add("limitLeft", lastLimit);
                    cmd5.Parameters.Add("custID", custId);
                    cmd5.ExecuteNonQuery();
                    SqlCommand cmd6 = new SqlCommand("UPDATE SAVING_ACCOUNT SET balance = (balance-@balance) WHERE custID = @custID", con);
                    cmd6.Parameters.Add("balance", Amount.Text);
                    cmd6.Parameters.Add("custID", custId);
                    cmd6.ExecuteNonQuery();
                  
                    // We don't handl the PowerShop
                    //SqlCommand cmd7 = new SqlCommand("UPDATE SAVING_ACCOUNT SET balance = (balance+@balance) WHERE custID = @custID", con);
                    //cmd7.Parameters.Add("balance", Amount.Text);
                    //cmd7.Parameters.Add("custID", TextBox3.Text);
                    //cmd7.ExecuteNonQuery();
                    con.Close();
                    Label6.Text = "SUCCESS";
                    Label11.Text = "payment";

                    Proceed.Visible = true;


                }

                else
                {

                    Response.Write("Invalid card no and PIN");

                }

            }
            else if (limit < 0)
            {
                Label6.Text = "You have reached your limit of spending for this month, please contact our admin to increase your spending limit.";
                Total.Enabled = false;
                Amount.Enabled = false;
                limit = limit + amount;
                Total.Text = limit.ToString();
                Password.Text = "******";
                Amount.Text = "";
                ComName.Text = "";
                Card.Text = "";

            }
            else
            {
                Label6.Text = "You have reached your limit.";
                Total.Enabled = false;

            }
        }
        else
        {
            Label6.Text = "Please enter an amount.";
        }

    }



    protected void Button2_Click(object sender, EventArgs e)
    {
        if (Cost.Text != null)
        {


            double amount = Convert.ToDouble(this.Cost.Text);
            double number = Convert.ToDouble(this.Number.Text);
            double total = Convert.ToDouble(Amount.Text);

            total = number * amount;

            Amount.Text = total.ToString();
            AmountTransfer.Text = total.ToString();

        }
    }
    public string custId { get; set; }
    public string Email { get; set; }
    public string passwordEmail { get; set; }
    protected void Button3_Click(object sender, EventArgs e)
    {
        Response.Redirect("OnlineSales.aspx");
    }
    protected void Proceed_Click(object sender, EventArgs e)
    {
        String custId = Session["userId"] as String;
        Session["limitLeft"] = Total.Text;

        SqlConnection con = DBManager.getSqlConnection();
        con.Open();

        Session["amountSpent"] = Amount.Text;
        Session["userId"] = custId;
        Session["amountSpent"] = AmountTransfer.Text;
        Server.Transfer("~/product/card/user/RewardConvertion.aspx");


    }

    public string TransID { get; set; }




    protected void SqlDataSource2_Selecting(object sender, SqlDataSourceSelectingEventArgs e)
    {

    }





    public string PIN { get; set; }
    public string question { get; set; }


    public string result { get; set; }

    public static byte[] bytes { get; set; }

    public object lastLimit { get; set; }


}